package com.qingyun.web.security.service;

import cn.hutool.core.lang.Validator;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qingyun.common.constant.TenantConstants;
import com.qingyun.common.core.domain.entity.SysUser;
import com.qingyun.common.core.domain.model.LoginUser;
import com.qingyun.common.core.domain.model.TiktokUser;
import com.qingyun.common.enums.UserStatus;
import com.qingyun.framework.web.service.SysPermissionService;
import com.qingyun.security.config.TenantContextHolder;
import com.qingyun.security.enums.App;
import com.qingyun.security.enums.LoginRole;
import com.qingyun.security.model.shop.AppLoginUser;
import com.qingyun.security.model.shop.AppMiniAppBody;
import com.qingyun.security.model.shop.AuthoAppConnect;
import com.qingyun.security.model.tiktok.TikTokLoginUser;
import com.qingyun.security.service.MyUserDetailService;
import com.qingyun.shop.service.IAuthoAppConnectService;
import com.qingyun.system.service.ISysUserService;
import com.qingyun.tiktok.service.ITiktokUserService;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 用户验证处理
 *
 * @author ruoyi
 */
@Service
@AllArgsConstructor
public class UserDetailsServiceImpl implements MyUserDetailService {
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);


    private ISysUserService userService;

    private SysPermissionService permissionService;

    private ITiktokUserService tiktokUserService;
//
    private IAuthoAppConnectService authoAppConnectService;






    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Integer tenantType = TenantContextHolder.getTenantType();
        LoginRole loginRoleType = LoginRole.getLoginRoleType(tenantType);
        switch (loginRoleType) {
            case SYS:
                return sysUserByUsername(username);
			case TIKTOK:
				return tiktokUserByOpen(username);
			case WXMALOGIN:
                return sysShopWxLoginUserNameOrPhone(username);
        }
        return null;
    }


    /**
     * 管理员用户信息
     *
     * @param username
     * @return
     */
    public UserDetails sysUserByUsername(String username) {
        SysUser user = userService.selectUserByUserName(username);
        if (Validator.isNull(user)) {
            log.info("登录用户：{} 不存在.", username);
            throw new UsernameNotFoundException("您的账号或密码错误");
        } else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            log.info("登录用户：{} 已被删除.", username);
//            throw new AuthoException("对不起，您的账号：" + username + " 已被删除");
            throw new UsernameNotFoundException("您的账号或密码错误");
        } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", username);
//            throw new AuthoException("对不起，您的账号：" + username + " 已停用");
            throw new UsernameNotFoundException("对不起，您的账号：" + username + " 已停用");
        }


        return createLoginUser(user);
    }

    public UserDetails createLoginUser(SysUser user) {
        return new LoginUser(user, permissionService.getMenuPermission(user));
    }

    public UserDetails sysShopWxLoginUserNameOrPhone(String userName){
		SysUser user = userService.selectUserByUserNameOrPhone(userName);
		if (Validator.isNull(user)) {
			log.info("登录用户：{} 不存在.",userName);
			throw new UsernameNotFoundException("您的账号或密码错误");
		} else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
			log.info("登录用户：{} 已被删除.", userName);
//            throw new AuthoException("对不起，您的账号：" + username + " 已被删除");
			throw new UsernameNotFoundException("您的账号或密码错误");
		} else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
			log.info("登录用户：{} 已被停用.", userName);
//            throw new AuthoException("对不起，您的账号：" + username + " 已停用");
			throw new UsernameNotFoundException("对不起，您的账号：" + userName + " 已停用");
		}
		AppLoginUser appLoginUser = new AppLoginUser(user,null);
		return appLoginUser;
	}

	/**
	 * 抖音登陆用户信息
	 * @return
	 */
	public UserDetails  tiktokUserByOpen(String openid){
		TiktokUser tiktokUser = tiktokUserService.getOne(Wrappers.lambdaQuery(TiktokUser.class).eq(TiktokUser::getOpenId, openid));
		TikTokLoginUser tikTokLoginUser = new TikTokLoginUser(tiktokUser,null);
		return tikTokLoginUser;
	}


    @Override
    public AuthoAppConnect loadUserByAppIdAndBizUserId(App app, String openId) {
        LambdaQueryWrapper<AuthoAppConnect> where = new LambdaQueryWrapper<AuthoAppConnect>();
//        where.eq(AuthoAppConnect::getEntryType, TenantConstants.MANAGE)
                where.eq(AuthoAppConnect::getUserType, app.value())
                .eq(AuthoAppConnect::getOpenId, openId);
         AuthoAppConnect user = authoAppConnectService.getOne(where);
        if (user == null) {
            throw new UsernameNotFoundException("user not find");
        }
        return user;
    }

    @Override
    public void insertUserIfNecessary(AuthoAppConnect authoAppConnect) {
        authoAppConnectService.save(authoAppConnect);
    }
}
